
#include "server.h"
namespace Frpc
{
	Router Server::_router;
	bool allow_ip(WFConnection *) { return true; }
	bool allow_auth(Context *ctx, RequestMsg *req)
	{
		if (ctx->user_id > 0 || req->is_login_cmd())
		{
			return true;
		}
		else
		{ 
			return false;
		}
	};
	void Server::task_handler(WFNetworkTask<RequestMsg, ReplyMsg> *task)
	{

		LOG("prepare handler task,state:%d.seq id:%lld",task->get_state(),task->get_task_seq());

		auto conn = task->get_connection();
		if (allow_ip(conn) == false)
		{
			task->get_resp()->set_bad_output(Status::Forbidden, "your ip is not allowed.");
			task->set_keep_alive(0);
			return;
		}
		auto ctx = (Context *)conn->get_context();
		auto req = task->get_req();
		if (allow_auth(ctx, req) == false)
		{DLOG("user not log in.");
			task->get_resp()->set_bad_output(Status::Unauthorized, "Unauthorized.");
			task->set_keep_alive(0);
			return;
		}
		auto reply = task->get_resp();
		reply->set_request_seq(req->request_seq());
		ctx->task = (ServerTask *)task;
		DLOG("start handle cmd:0x%X",req->get_cmd());
		Server::_router.handle(req, reply, ctx);
		//if (task->get_state() != WFT_STATE_SUCCESS)
		//	{	DLOG("task state error after handler");
		//		task->set_keep_alive(1);
		//	}
	}

	WFConnection *Server::new_connection(int accept_fd)
	{
		WFConnection *conn = this->WFServer::new_connection(accept_fd);

		if (conn)
		{
			DLOG("new connection fd: %d",accept_fd);
			auto ctx = new Context;
			conn->set_context(ctx, [](void *p)
							  { delete (Context *)p; DLOG("connection obj deleted.");});
			return conn;
		}

		return NULL;
	}

	CommSession *Server::new_session(long long seq, CommConnection *conn)
	{
		//	static mysql_process_t empty = [](WFMySQLTask *){ };
		//	WFMySQLTask *task;
	auto task=new ServerTask(this, this->process);

		//	task = WFServerTaskFactory::create_mysql_task(this, seq ? this->process :  empty);
		//	task->set_keep_alive(this->params.keep_alive_timeout);
		//	task->set_receive_timeout(this->params.receive_timeout);
		//	task->get_req()->set_size_limit(this->params.request_size_limit);
	
	//DLOG("session created,seq:%lld",seq);
		return task;
	}

}